package jevon.philautus.controller;

import javax.validation.Valid;

import jevon.philautus.domain.User;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("/")
public class SecurityController {

	@RequestMapping(value="/login",method = RequestMethod.GET)
	public String addNew(Model model) {
		model.addAttribute(new User());
		return "/login/new";
	}

	@RequestMapping(value="/login",method = RequestMethod.POST)
	public String login(@Valid User user, BindingResult result) {
		if (result.hasErrors()) {
			return "/login/new";
		}
		UsernamePasswordToken token = new UsernamePasswordToken(
				user.getUsername(), user.getPasswd(), true);
		try {
			SecurityUtils.getSubject().login(token);
		} catch (AuthenticationException e) {
			result.rejectValue("username", "username or password invalid!");
		}
		if (result.hasErrors()) {
			return "/login/new";
		}

		return "redirect:/";
	}

	@RequestMapping(value = "/logout", method = RequestMethod.GET)
	public String logout(Model model) {
		model.addAttribute(new User());
		SecurityUtils.getSubject().logout();
		return "/login/new";
	}
}
